<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ContextKey;
use App\Constants\ErrorCode;
use App\Dao\UserDao;
use App\Exception\BusinessException;
use App\Model\User;
use App\Utils\Log;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Constants\Model\User as UserConstants;

class ClientUserMiddleware implements MiddlewareInterface
{
    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        /** @var User $userInfo */
        $userInfo = Context::get(ContextKey::USER);
        
        //用户被封
        if ($userInfo->status != UserConstants::STATUS_UNBLOCK) {
            throw new BusinessException(ErrorCode::USER_DISABLE);
        }

        //切换悬赏主时
        $cooperative_id = $userInfo->cooperative_id;
        if ($request->hasHeader('cooperative_id')) {
            $tmp_cooperative_id = $request->getHeaderLine('cooperative_id');
            if ($tmp_cooperative_id != ''
                && $tmp_cooperative_id != '-1'
                && $cooperative_id != $tmp_cooperative_id
            ) {
                $cooperative_id = $tmp_cooperative_id;

                $newUserInfo = $this->userDao->first(
                    [
                        'cooperative_id' => $cooperative_id,
                        'phone' => $userInfo->phone
                    ]
                );

                if ($newUserInfo->count() == 0) {
                    throw new BusinessException(ErrorCode::USER_NOT_EXIST);
                }

                Context::set(ContextKey::USER, $newUserInfo);
            }
        }
        return $handler->handle($request);
    }

}